package com.zrrd.reggie.common;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

//拦截指定类型的控制器
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
public class GloabExceptionHandler {

    //集体处理某个异常的方法
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex) {
        //获取异常信息
        String message = ex.getMessage();

        //出现未知错误加上这个方便查看报错
//        System.out.println("拦截到了=======>" + message);

        //判断当前异常信息是否包含指定的内容
        if (message.contains("Duplicate entry")) {
            //付异常信息字符串切割  根据空格切割
            String[] split = message.split(" ");
            //获取数组中参数的信息并返回错误信息
            String msg = split[2] + "已存在";
            return R.error(msg);
        }
        return R.error("未知错误");
    }

    @ExceptionHandler(CustException.class)
    public R<String> CustException(CustException e) {
        System.out.println("拦截到了自定义异常====>" + e.getMessage());
        return R.error(e.getMessage());
    }

}
